/*
 * Copyright (c) 2008, Magrathean Research
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the Magrathean Technologies, British Columbia, Canada nor the names of its contributors may be used to 
      endorse or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Material2High
{
    public partial class lgh : Form
    {
        FileSystemInfo[] files;

        public lgh()
        {
            InitializeComponent();
        }

        private void fromBtn_Click(object sender, EventArgs e)
        {
            if (fromFolderDialog.ShowDialog() == DialogResult.OK)
            {
                fromTextBox.Text = fromFolderDialog.SelectedPath;

                System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(fromFolderDialog.SelectedPath);

                files = dirInfo.GetFiles();

                addFiles(false);
            }
        }

        private void toBtn_Click(object sender, EventArgs e)
        {
            if (toFolderDialog.ShowDialog() == DialogResult.OK)
            {
                toTextBox.Text = toFolderDialog.SelectedPath;
            }
        }

        private void fileOptionsCheckAllBtn_Click(object sender, EventArgs e)
        {
            addFiles(true);
        }

        private void addFiles(bool isChecked)
        {
            filesCheckedListBox.Items.Clear();

            if (isChecked)
            {
                foreach (FileSystemInfo eachFile in files)
                {
                    if (eachFile.Extension.ToLower() == ".material")
                        filesCheckedListBox.Items.Add(eachFile.FullName.ToString(), true);
                }
            }
            else
            {
                foreach (FileSystemInfo eachFile in files)
                {
                    if (eachFile.Extension.ToLower() == ".material")
                        filesCheckedListBox.Items.Add(eachFile.FullName.ToString());
                }
            }

            if (filesCheckedListBox.Items.Count == 0)
            {
                MessageBox.Show("No '.material' file(s) found in this folder:" + Environment.NewLine + fromTextBox.Text, "Warning...", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                fromTextBox.Clear();
                totalFilesLabel.Text = "Material 2 High Material";
                
                fileOptionsCheckNoneBtn.Enabled =
                fileOptionsCheckAllBtn.Enabled =
                simGoBtn.Enabled =
                from2toBtn.Enabled =
                goBtn.Enabled = false;
            }
            else
            {
                totalFilesLabel.Text = "Total Files Loaded (" + filesCheckedListBox.Items.Count.ToString() + ")";

                fileOptionsCheckNoneBtn.Enabled =
                fileOptionsCheckAllBtn.Enabled =
                simGoBtn.Enabled =
                from2toBtn.Enabled =
                goBtn.Enabled = true;
            }
        }

        private void fileOptionsCheckNoneBtn_Click(object sender, EventArgs e)
        {
            addFiles(false);
        }

        private void goBtn_Click(object sender, EventArgs e)
        {
            if (toTextBox.Text == "")
            {
                MessageBox.Show("There is no destination set!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                progressBar.Style = ProgressBarStyle.Marquee;

                progressBar.Visible = true;

                if (MessageBox.Show("Are you sure you wish to run the process?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    convertToHighMaterial();
                }
                else
                {
                    progressBar.Visible = false;
                }
            }
        }

        private void from2toBtn_Click(object sender, EventArgs e)
        {
            toTextBox.Text = fromTextBox.Text;
        }

        private void convertToHighMaterial()
        {
            progressBar.Style = ProgressBarStyle.Continuous;

            progressBar.Maximum = filesCheckedListBox.Items.Count;

            for (int i = 0; i < filesCheckedListBox.Items.Count; i++)
            {
                progressBar.PerformStep();

                FileInfo theOriginalFile = new FileInfo(filesCheckedListBox.Items[i].ToString());
                
                CheckState isFileChecked = filesCheckedListBox.GetItemCheckState(i);

                string finalOutput = null;

                StreamReader re = File.OpenText(theOriginalFile.FullName);

                string input = null;
                string materialName = null;
                string FirstHighMatPath = null;
                string SecondHighMatPath = null;
                string ThirdHighMatPath = null;
                string TheOriginalFileName = null;
                string TheHighMatFileName = null;

                while ((input = re.ReadLine()) != null)
                {
                    string cleanInput = input.Trim();

                    string[] splitInput = cleanInput.Split(new Char[] { ' ' });

                    if (splitInput[0].ToLower() == "material")
                    {
                        materialName = splitInput[1].ToString();
                    }
                    else if (splitInput[0].ToLower() == "texture")
                    {
                        string[] splitDDSInput = splitInput[1].Split(new Char[] { '.' });

                        FirstHighMatPath = splitInput[1].ToString();
                        SecondHighMatPath = splitDDSInput[0].ToString() + "_DISP." + splitDDSInput[1].ToString();
                        ThirdHighMatPath = splitDDSInput[0].ToString() + "_NRM.tga";
                        TheOriginalFileName = materialName;
                        TheHighMatFileName = materialName.Replace(".dds", ".highMaterial");
                    }
                }

                re.Close();

                if (isFileChecked.ToString().ToLower() == "checked")
                {
                    finalOutput = buildFPSWeaponMaterialFile(FirstHighMatPath, SecondHighMatPath, ThirdHighMatPath, TheHighMatFileName);
                }
                else
                {
                    finalOutput = buildShaderBaseMaterialFile(FirstHighMatPath, SecondHighMatPath, ThirdHighMatPath, TheHighMatFileName);
                }

                FileInfo theNewFile = new FileInfo(toTextBox.Text + @"\" + TheHighMatFileName);

                StreamWriter writeNewFile = theNewFile.CreateText();

                writeNewFile.Write(finalOutput);
                writeNewFile.Close();
            }

            MessageBox.Show("Process Complete!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

            progressBar.Visible = false;
        }

        private string buildFPSWeaponMaterialFile(string first, string second, string third, string newFileName)
        {
            StringBuilder file = new StringBuilder();

            file.AppendLine("highLevelMaterial " + newFileName);
            file.AppendLine("{");
            file.AppendLine("\ttemplate = FPSWeaponMaterial");
            file.AppendLine("\tspecularScale = 1.392157 1.392157 1.392157");
            file.AppendLine("\tspecularShininess = 42");
            file.AppendLine("\theightFromNormalMapAlpha = True");

            file.AppendLine("\tdiffuse1Map");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + first);
            file.AppendLine("\t}");

            file.AppendLine("\tspecularMap");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + second);
            file.AppendLine("\t}");

            file.AppendLine("\tnormalMap");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + third);
            file.AppendLine("\t}");

            file.AppendLine("}");

            return file.ToString();
        }

        private string buildShaderBaseMaterialFile(string first, string second, string third, string newFileName)
        {
            StringBuilder file = new StringBuilder();

            file.AppendLine("highLevelMaterial " + newFileName);
            file.AppendLine("{");
            file.AppendLine("\ttemplate = ShaderBaseMaterial");
            file.AppendLine("\tspecularScale = 1.392157 1.392157 1.392157");
            file.AppendLine("\theightFromNormalMapAlpha = True");
            
            file.AppendLine("\tdiffuse1Map");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + first);
            file.AppendLine("\t}");

            file.AppendLine("\tspecularMap");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + second);
            file.AppendLine("\t}");

            file.AppendLine("\tnormalMap");
            file.AppendLine("\t{");
            file.AppendLine("\t\ttexture = " + third);
            file.AppendLine("\t}");

            file.AppendLine("}");

            return file.ToString();
        }
    }
}